package com.chatplus.application.config.extend;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

/**
 * 在上下文初始化前，完成自定义配置注册
 *
 * @Author Angus
 * @Date 2024/3/31
 */
public class ExtendConfigContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ExtendConfigContextInitializer.class);

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        LOGGER.message("postProcessEnvironment#initialize").info();
        ConfigurableEnvironment env = configurableApplicationContext.getEnvironment();
        initialize(env);
    }

    protected void initialize(ConfigurableEnvironment environment) {
        if (environment.getPropertySources().contains("ExtendSource")) {
            // 已经初始化过了，直接忽略
            return;
        }
        MapPropertySource propertySource = new MapPropertySource("ExtendSource", ExtendConfigContext.getInstance().getCache());
        environment.getPropertySources().addFirst(propertySource);
    }
}
